package org.hilo.boot.app.component;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import org.hilo.boot.core.web.HttpServletRequestHelper;

/**
 * Gloabal Controller Interceptor
 * @see HandlerInterceptorAdapter
 * 
 * @author zollty
 * @since 2018-2-23
 */
@Component
public class GloabalControllerInterceptor extends HandlerInterceptorAdapter {
    @Value("${hilo.web.trace-request:}")
    private String[] traceRequest;
    private Logger reqLog;
    private Boolean trace;
    private boolean traceAPI;
    @Value("${hilo.web.enable-i18n:false}")
    private boolean enableI18n;
    @Value("${hilo.web.trace-request-body:false}")
    private boolean traceBody;

    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler)
            throws Exception {
        
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        if (enableI18n) {
            /**
             * 设置locale，供临时使用，参见：{@link #GlobalResponseBodyAdvice}
             */
            Locale locale = request.getLocale();
            if (locale != null) {
                response.addHeader("locale", request.getLocale().toString());
            }
        }

        if (getTrace()) {
            if (reqLog == null) {
                reqLog = LoggerFactory.getLogger("reqLog");
            }
            if (reqLog.isDebugEnabled()) {
                if (traceAPI) {
                    reqLog.debug(HttpServletRequestHelper.getRequestInfo(request, traceBody, false));
                } else {
                    String uri = request.getRequestURI();
                    for (String prefix : traceRequest) {
                        if (uri.startsWith(prefix)) {
                            reqLog.debug(HttpServletRequestHelper.getRequestInfo(request, traceBody, false));
                            break;
                        }
                    }
                }
            }
        }

        return true;
    }

    public Boolean getTrace() {
        if (trace == null) {
            if (traceRequest.length == 0) {
                trace = false;
            } else {
                trace = true;
                if (traceRequest[0].equals("all")) {
                    trace = false;
                } else if (traceRequest[0].equals("api")) {
                    traceAPI = true;
                }
            }
        }
        return trace;
    }

}
